package ctrl;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.component.LabelField;
import weibo.model.Comment;
import weibo.model.Status;
import code.Config;
import code.Function;

public class StatusesListStyleButtonField extends Field
{
    public static int DRAWPOSITION_TOP = 0;
    public static int DRAWPOSITION_BOTTOM = 1;
    public static int DRAWPOSITION_MIDDLE = 2;
    public static int DRAWPOSITION_SINGLE = 3;
    
    private static final int CORNER_RADIUS = 12;
    
    private static final int HPADDING = Display.getWidth() <= 320 ? 4 : 6;
    private static final int VPADDING = 4;
    
    private static final int COLOR_BACKGROUND = 0xFFFFFF;
    //private static final int COLOR_BACKGROUND_TITLE = 0xA9A9A9;
    private static final int COLOR_BORDER = 0xBBBBBB;
    //private static final int COLOR_BACKGROUND_FOCUS = 0x186DEF;
    private static final int COLOR_BACKGROUND_FOCUS = 0x054800;//0x0A9000;
    
    private MyLabelField _labelScreenName;
    private MyLabelField _labelText;
    private MyLabelField _labelTime;
    private MyLabelField _labelSource;
    private MyLabelField _labelText_Retweet;
    
    private Bitmap _avatarIcon;
    private Bitmap _image_Status;
    private Bitmap _image_Retweet;
    
    private int _rightOffset;
    private int _leftOffset;
    private int _labelHeight;
    
    private int _drawPosition = -1;

    public StatusesListStyleButtonField(Status status)
    {
        super(USE_ALL_WIDTH | Field.FOCUSABLE);

    	String screen_name=status.getUser().getScreenName();
    	String time=status.getCreatedAtShort();
    	String text=status.getText();
    	String source=status.getSource().getName();
    	String[] images=status.getPicUrls().getThumbnailPics();
    	Status status_Retweet=status.getRetweetedStatus();

    	_avatarIcon=Bitmap.getBitmapResource("avatar.png");
        if(screen_name!=null) {_labelScreenName = new MyLabelField(screen_name, LabelField.ELLIPSIS); _labelScreenName.setFont(Config.FONT_SCREENNAME);}
        if(time!=null) {_labelTime=new MyLabelField(time);}
        if(text!=null) {_labelText=new MyLabelField(text);}
        if(source!=null) {_labelSource=new MyLabelField("来自 "+source); _labelSource.setFont(Config.FONT_SOURCE);}
        if(images!=null) {_image_Status=Bitmap.getBitmapResource("status_image.png");}

        String[] images_Retweet=null;
        if(status_Retweet!=null)
        {
        	if(status_Retweet.isDeleted())
        	{
        		_labelText_Retweet=new MyLabelField(status_Retweet.getText());
        	} else {
            	String screenname_Retweet=status_Retweet.getUser().getScreenName();
            	String text_Retweet=status_Retweet.getText();
            	images_Retweet=status_Retweet.getPicUrls().getThumbnailPics();
            	
                if(screenname_Retweet!=null && text_Retweet!=null) {_labelText_Retweet=new MyLabelField("@" + screenname_Retweet + " :" + text_Retweet);}
                if(images_Retweet!=null) {_image_Retweet=Bitmap.getBitmapResource("status_image.png");}
        	}
        }
    }        

    public StatusesListStyleButtonField(Comment comment)
    {
        super(USE_ALL_WIDTH | Field.FOCUSABLE);

    	String screen_name=comment.getUser().getScreenName();
    	String time=comment.getCreatedAtShort();
    	String text=comment.getText();
    	String source=comment.getSource().getName();
    	Status status_Retweet=comment.getStatus();
        Comment reply_comment=comment.getReplycomment();
        
    	_avatarIcon=Bitmap.getBitmapResource("avatar.png");
        if(screen_name!=null) {_labelScreenName = new MyLabelField(screen_name, LabelField.ELLIPSIS); _labelScreenName.setFont(Config.FONT_SCREENNAME);}
        if(time!=null) {_labelTime=new MyLabelField(time);}
        if(text!=null) {_labelText=new MyLabelField(text);}
        if(source!=null) {_labelSource=new MyLabelField("来自 "+source); _labelSource.setFont(Config.FONT_SOURCE);}

        if(reply_comment!=null)
        {
        	String screenname_ReplyTo=reply_comment.getUser().getScreenName();
        	String text_ReplyTo=reply_comment.getText();
        	
        	_labelText_Retweet=new MyLabelField("@" + screenname_ReplyTo + " :" + text_ReplyTo);
        } else {
            String[] images_Retweet=null;
            if(status_Retweet!=null)
            {
            	if(status_Retweet.isDeleted())
            	{
            		_labelText_Retweet=new MyLabelField(status_Retweet.getText());
            	} else {
            		String screenname_Retweet=status_Retweet.getUser().getScreenName();
                	String text_Retweet=status_Retweet.getText();
                	images_Retweet=status_Retweet.getPicUrls().getThumbnailPics();
                	
                    if(screenname_Retweet!=null && text_Retweet!=null) {_labelText_Retweet=new MyLabelField("@" + screenname_Retweet + " :" + text_Retweet);}
                    if(images_Retweet!=null) {_image_Retweet=Bitmap.getBitmapResource("status_image.png");}
            	}
            }
        }
    }        

    public void setDrawPosition( int drawPosition ) {_drawPosition = drawPosition;}
    
    public void layout(int width, int height)
    {
    	_labelHeight=VPADDING;
        _leftOffset = HPADDING;
        _rightOffset = HPADDING;
        
        if(_avatarIcon!=null) {_leftOffset += _avatarIcon.getWidth() + HPADDING;}

        if(_labelTime!=null) {_labelTime.layout(width- _leftOffset - _rightOffset, height);}
        
        if(_labelScreenName!=null)
        {
        	int intWidth=_labelTime!=null ? _labelTime.getWidth() : 0;
        	_labelScreenName.layout(width - _leftOffset - _rightOffset - intWidth, height);
            _labelHeight += _labelScreenName.getHeight();	
        }
        
        if(_labelText!=null)
        {
        	_labelText.layout(width - _leftOffset - _rightOffset, height);
        	_labelHeight+=_labelText.getHeight()+VPADDING;
        	
            if(_image_Status!=null) {_labelHeight+=_image_Status.getHeight()+VPADDING;}
            
            if(_labelText_Retweet!=null)
            {
            	_labelText_Retweet.layout(width - _leftOffset - _rightOffset, height);
            	_labelHeight+=_labelText_Retweet.getHeight() + 2*VPADDING;
            	
                if(_image_Retweet!=null) {_labelHeight+=_image_Retweet.getHeight()+VPADDING;}
            }
        }
        
        if(_avatarIcon!=null) {_labelHeight=(_avatarIcon.getHeight()>=_labelHeight) ? _avatarIcon.getHeight()+2*VPADDING : _labelHeight;}
        
        if(_labelSource!=null)
        {
        	_labelSource.layout(width-_leftOffset-_rightOffset, height);
        	_labelHeight+=_labelSource.getHeight()+2*VPADDING;
        }
        
        setExtent(width, _labelHeight);
    }
    
    public void setAvatarIcon(byte[] data)
    {
    	if(_avatarIcon!=null && data!=null)
    	{
    		EncodedImage image=EncodedImage.createEncodedImage(data, 0, data.length);
    		_avatarIcon=image.getBitmap();
    		
    		invalidate();
    		//updateLayout();
    	}
    }
    
    public void setStatusImage(byte[] data)
    {
    	if(_image_Status!=null && data!=null)
    	{
    		EncodedImage image=EncodedImage.createEncodedImage(data, 0, data.length);
    		_image_Status=Function.bestFit(image, 80, 80);
    		
    		invalidate();
    		//updateLayout();
    	}
    }
    
    public void setRetweetImage(byte[] data)
    {
    	if(_image_Retweet!=null && data!=null)
    	{
    		EncodedImage image=EncodedImage.createEncodedImage(data, 0, data.length);
    		_image_Retweet=Function.bestFit(image, 80, 80);
    		
    		invalidate();
    		//updateLayout();
    	}
    }
    
    protected void paint(Graphics g)
    {
    	int currentTop=VPADDING;
    	
        // Avatar Bitmap
        if(_avatarIcon != null)
        {
            g.drawBitmap(HPADDING, currentTop, _avatarIcon.getWidth(), _avatarIcon.getHeight(), _avatarIcon, 0, 0);
        }
        
        // Screen name Text
        try {
            g.pushRegion(_leftOffset, currentTop, getWidth() - _leftOffset - _rightOffset, _labelScreenName.getHeight(), 0, 0);
            g.setFont(Config.FONT_SCREENNAME);
            _labelScreenName.paint(g);
        } finally {g.popContext();}
        
        // Time Text
        if(_labelTime !=null)
        {
        	try {
        		g.pushRegion(getWidth() - _labelTime.getWidth()-_rightOffset, currentTop, _labelTime.getWidth(), _labelTime.getHeight(),0,0);
        		_labelTime.paint(g);
        	} finally{g.popContext();}
        }
        
        // Status Text
        if(_labelText !=null)
        {
        	currentTop+=_labelScreenName.getHeight();
        	
        	try {
        		Graphics oldG=g;
        		g.pushRegion(_leftOffset+HPADDING, currentTop, getWidth()-_leftOffset-_rightOffset, _labelText.getHeight(), 0, 0);
        		g.setColor(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? Color.WHITE : Color.GRAY);

        		_labelText.paint(g);
        		
        		g=oldG;
        	} finally{g.popContext();}
        	
        	currentTop+=_labelText.getHeight()+VPADDING;
        	
            if(_image_Status!=null)
            {
           		g.drawBitmap(_leftOffset+HPADDING, currentTop, _image_Status.getWidth(), _image_Status.getHeight(), _image_Status, 0, 0);
           		
           		currentTop+=_image_Status.getHeight()+VPADDING;
            }
        }
        
        // Retweeted Status Text
        if(_labelText_Retweet!=null)
        {
        	currentTop+=VPADDING;
        	
        	try {
        		Graphics oldG=g;
        		
        		g.pushRegion(_leftOffset+HPADDING, currentTop, getWidth()-_leftOffset-_rightOffset, _labelText_Retweet.getHeight(), 0, 0);
       			g.setColor(Color.ORANGE);
        		_labelText_Retweet.paint(g);
        		
        		g=oldG;
        	} finally{g.popContext();}
        	
        	currentTop+=_labelText_Retweet.getHeight()+VPADDING;
        	
            if(_image_Retweet!=null)
            {
           		g.drawBitmap(_leftOffset+HPADDING, currentTop, _image_Retweet.getWidth(), _image_Retweet.getHeight(), _image_Retweet, 0, 0);
           		
           		currentTop+=_image_Retweet.getHeight()+VPADDING;
            }
        }
        
        // Source
        if(_labelSource!=null)
        {
        	if(currentTop<_avatarIcon.getHeight())
        	{
        		currentTop=_avatarIcon.getHeight()+3*VPADDING;
        	} else {
        		currentTop+=VPADDING;	
        	}
        	
    		try {
    			Graphics oldG=g;
        		g.pushRegion(2*HPADDING, currentTop, _labelSource.getWidth(), _labelSource.getHeight(),0,0);
        		g.setColor(Color.DARKGRAY);
        		_labelSource.setFont(Config.FONT_SOURCE);
        		_labelSource.paint(g);
        		g=oldG;
        	} finally{g.popContext();}
        }
    }
    
    protected void paintBackground(Graphics g)
    {
        if(_drawPosition < 0)
        {
            super.paintBackground(g);
            return;
        }
        
        int oldColour = g.getColor();
        
        int background = g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS) ? COLOR_BACKGROUND_FOCUS : COLOR_BACKGROUND;
        
        try {
            if(_drawPosition == 0)
            {
                // Top
                g.setColor(background);
                g.fillRoundRect(0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            } else if(_drawPosition == 1) {
                // Bottom 
                g.setColor(background);
                g.fillRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
            } else if(_drawPosition == 2) {
                // Middle
                g.setColor(background);
                g.fillRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS);
                g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            } else {
                // Single
                g.setColor(background);
                g.fillRoundRect(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS);
                g.setColor(COLOR_BORDER);
                g.drawRoundRect(0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS);
            }
        } finally {
            g.setColor(oldColour);
        }
    }
    
    protected void drawFocus(Graphics g, boolean on)
    {
        if(_drawPosition < 0)
        {
            super.drawFocus(g, on);
        } else {
            boolean oldDrawStyleFocus = g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS);
            
            try {
                if(on)
                {
                	g.setColor(Color.WHITE);
                    g.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, true);
                }
                
                paintBackground(g);
                paint(g);
            } finally {
                g.setDrawingStyle(Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus);
            }
        }
    }
    
    protected boolean keyChar(char character, int status, int time) 
    {
        if(character == Characters.ENTER)
        {
            clickButton();
            return true;
        }
        
        return super.keyChar(character, status, time);
    }
    
    protected boolean navigationClick(int status, int time) 
    {
        clickButton(); 
        return true;    
    }
    
    protected boolean trackwheelClick(int status, int time)
    {        
        clickButton();    
        return true;
    }
    
    protected boolean invokeAction(int action) 
    {
        switch(action)
        {
            case ACTION_INVOKE:
                clickButton(); 
                return true;
        }
        
        return super.invokeAction(action);
    }

    public void clickButton() {fieldChangeNotify(0);}
       
    protected boolean touchEvent(TouchEvent message)
    {
        int x = message.getX(1);
        int y = message.getY(1);
        
        if(x < 0 || y < 0 || x > getExtent().width || y > getExtent().height) {return false;}
        
        switch(message.getEvent())
        {
        	case TouchEvent.CLICK:
                clickButton();
                return true;
        }
        
        return super.touchEvent(message);
    }

    public void setDirty( boolean dirty ) {}
    public void setMuddy( boolean muddy ) {}
}